package com.example.apricots;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.apricots.Base.App;
import com.example.apricots.bean.User;
import com.example.apricots.bean.greendao.UserDao;
import com.example.apricots.db.DBManager;

import java.util.List;

public class ActivityUpdatePwd extends AppCompatActivity implements View.OnClickListener {

    Button btn_back;
    Button btn_confirm;
    Button btn_cancel;
    EditText ed_pwd_old;
    EditText ed_pwd_new;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_pwd);
        initview();
    }

    private void initview() {
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_confirm = findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(this);
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
        ed_pwd_old = findViewById(R.id.ed_pwd_old);
        ed_pwd_new = findViewById(R.id.ed_pwd_new);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_confirm:
                confirmModify();
                break;

        }

    }

    private void confirmModify() {
        String pwd_old = ed_pwd_old.getText().toString();
        String pwd_new = ed_pwd_new.getText().toString();
        boolean isExistDB = querydata(pwd_old);

        if (pwd_old.equals("") || pwd_new.equals("")) {
            Toast.makeText(ActivityUpdatePwd.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        } else if (pwd_new.equals(pwd_old)) {
            Toast.makeText(this, "用户名和密码不能相同", Toast.LENGTH_SHORT).show();
            return;
        } else if (!isExistDB) {
            Toast.makeText(this, "修改失败,未查到该密码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            DBManager.getInstance().updateUserByPwd(pwd_old, pwd_new);
            Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show();
            finish();
            startActivity(new Intent(this, ActivityLogin.class));
        }

    }

    /**
     * 根据老密码去数据库查
     *
     * @param pwd
     * @return
     */
    private boolean querydata(String pwd) {
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        List<User> userList = userDao.queryBuilder().where(UserDao.Properties.Password.eq(pwd)).build().list();
        return userList.size() != 0 && userList != null;
    }
}
